﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.BOM;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class BOMForm : Form
    {
        private DataGridView dgvBOM;
        private Button btnRefresh;
        private Button btnAdd;
        private Button btnClear;
        
        // 输入控件
        private TextBox txtBOMCode;
        private TextBox txtBOMVersion;
        private TextBox txtPlanId;
        private TextBox txtMaterialId;
        private TextBox txtProductName;
        private TextBox txtSpecification;
        private TextBox txtUnitName;
        private TextBox txtMaterialCode;
        private TextBox txtMaterialName;
        
        // 选择按钮
        private Button btnSelectPlan;
        private Button btnSelectMaterial;

        // 添加生产计划数据属性
        public PlanData CurrentPlan { get; private set; }
        public bool IsDecomposed { get; private set; } = false;

        public BOMForm(PlanData planData = null)
        {
            InitializeComponent();
            CurrentPlan = planData;
            InitializeCustomComponents();
            LoadBOMData();
            
            // 如果有传入的生产计划数据，自动填充相关字段
            if (CurrentPlan != null)
            {
                FillPlanData();
            }
        }

        /// <summary>
        /// 填充生产计划数据到输入框
        /// </summary>
        private void FillPlanData()
        {
            if (CurrentPlan != null)
            {
                txtPlanId.Text = CurrentPlan.planId.ToString();
                txtProductName.Text = CurrentPlan.productName ?? "";
                txtSpecification.Text = CurrentPlan.specification ?? "";
                txtUnitName.Text = CurrentPlan.unitName ?? "";
                
                // 自动生成BOM编号和版本
                txtBOMCode.Text = $"BOM{CurrentPlan.planId:D4}";
                txtBOMVersion.Text = "1.0";
            }
        }

        private void InitializeCustomComponents()
        {
            // 设置窗体标题和大小
            this.Text = "BOM管理";
            this.Size = new Size(1600, 800);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 创建输入面板
            Panel inputPanel = new Panel();
            inputPanel.Dock = DockStyle.Top;
            inputPanel.Height = 250;
            inputPanel.BackColor = Color.LightGray;

            // 创建输入控件
            CreateInputControls(inputPanel);

            // 创建按钮面板
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Top;
            buttonPanel.Height = 50;
            buttonPanel.BackColor = Color.White;

            // 创建按钮
            CreateButtons(buttonPanel);

            // 创建DataGridView
            dgvBOM = new DataGridView();
            dgvBOM.Dock = DockStyle.Fill;
            dgvBOM.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvBOM.AllowUserToAddRows = false;
            dgvBOM.ReadOnly = true;
            dgvBOM.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvBOM.MultiSelect = false;
            dgvBOM.RowHeadersVisible = false;
            dgvBOM.BackgroundColor = Color.White;
            dgvBOM.GridColor = Color.LightGray;
            dgvBOM.BorderStyle = BorderStyle.None;

            // 添加控件到窗体
            this.Controls.Add(dgvBOM);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(inputPanel);
        }

        private void CreateInputControls(Panel panel)
        {
            // 创建标签和文本框
            int labelX = 20;
            int textBoxX = 120;
            int startY = 20;
            int spacing = 35;
            
            // 第二列的起始位置（确保不被第一列遮挡）
            int secondColumnLabelX = 320;  // 第一列按钮结束位置 + 间距
            int secondColumnTextBoxX = 420; // 第二列标签结束位置 + 间距

            // BOM编号
            Label lblBOMCode = new Label();
            lblBOMCode.Text = "BOM编号:";
            lblBOMCode.Location = new Point(labelX, startY);
            lblBOMCode.Size = new Size(80, 20);

            txtBOMCode = new TextBox();
            txtBOMCode.Location = new Point(textBoxX, startY);
            txtBOMCode.Size = new Size(150, 20);

            // BOM版本
            Label lblBOMVersion = new Label();
            lblBOMVersion.Text = "BOM版本:";
            lblBOMVersion.Location = new Point(secondColumnLabelX, startY);
            lblBOMVersion.Size = new Size(80, 20);

            txtBOMVersion = new TextBox();
            txtBOMVersion.Location = new Point(secondColumnTextBoxX, startY);
            txtBOMVersion.Size = new Size(150, 20);

            // 生产计划ID
            Label lblPlanId = new Label();
            lblPlanId.Text = "生产计划ID:";
            lblPlanId.Location = new Point(labelX, startY + spacing);
            lblPlanId.Size = new Size(80, 20);

            txtPlanId = new TextBox();
            txtPlanId.Location = new Point(textBoxX, startY + spacing);
            txtPlanId.Size = new Size(150, 20);

            // 选择生产计划按钮
            btnSelectPlan = new Button();
            btnSelectPlan.Text = "...";
            btnSelectPlan.Size = new Size(30, 20);
            btnSelectPlan.Location = new Point(textBoxX + 160, startY + spacing);
            btnSelectPlan.Click += BtnSelectPlan_Click;

            // 产品名称
            Label lblProductName = new Label();
            lblProductName.Text = "产品名称:";
            lblProductName.Location = new Point(secondColumnLabelX, startY + spacing);
            lblProductName.Size = new Size(80, 20);

            txtProductName = new TextBox();
            txtProductName.Location = new Point(secondColumnTextBoxX, startY + spacing);
            txtProductName.Size = new Size(150, 20);
            txtProductName.ReadOnly = true;

            // 规格型号
            Label lblSpecification = new Label();
            lblSpecification.Text = "规格型号:";
            lblSpecification.Location = new Point(labelX, startY + spacing * 2);
            lblSpecification.Size = new Size(80, 20);

            txtSpecification = new TextBox();
            txtSpecification.Location = new Point(textBoxX, startY + spacing * 2);
            txtSpecification.Size = new Size(150, 20);
            txtSpecification.ReadOnly = true;

            // 单位
            Label lblUnitName = new Label();
            lblUnitName.Text = "单位:";
            lblUnitName.Location = new Point(secondColumnLabelX, startY + spacing * 2);
            lblUnitName.Size = new Size(80, 20);

            txtUnitName = new TextBox();
            txtUnitName.Location = new Point(secondColumnTextBoxX, startY + spacing * 2);
            txtUnitName.Size = new Size(150, 20);
            txtUnitName.ReadOnly = true;

            // 物料ID
            Label lblMaterialId = new Label();
            lblMaterialId.Text = "物料ID:";
            lblMaterialId.Location = new Point(labelX, startY + spacing * 3);
            lblMaterialId.Size = new Size(80, 20);

            txtMaterialId = new TextBox();
            txtMaterialId.Location = new Point(textBoxX, startY + spacing * 3);
            txtMaterialId.Size = new Size(150, 20);

            // 选择物料按钮
            btnSelectMaterial = new Button();
            btnSelectMaterial.Text = "...";
            btnSelectMaterial.Size = new Size(30, 20);
            btnSelectMaterial.Location = new Point(textBoxX + 160, startY + spacing * 3);
            btnSelectMaterial.Click += BtnSelectMaterial_Click;

            // 物料编号
            Label lblMaterialCode = new Label();
            lblMaterialCode.Text = "物料编号:";
            lblMaterialCode.Location = new Point(secondColumnLabelX, startY + spacing * 3);
            lblMaterialCode.Size = new Size(80, 20);

            txtMaterialCode = new TextBox();
            txtMaterialCode.Location = new Point(secondColumnTextBoxX, startY + spacing * 3);
            txtMaterialCode.Size = new Size(150, 20);
            txtMaterialCode.ReadOnly = true;

            // 物料名称
            Label lblMaterialName = new Label();
            lblMaterialName.Text = "物料名称:";
            lblMaterialName.Location = new Point(labelX, startY + spacing * 4);
            lblMaterialName.Size = new Size(80, 20);

            txtMaterialName = new TextBox();
            txtMaterialName.Location = new Point(textBoxX, startY + spacing * 4);
            txtMaterialName.Size = new Size(150, 20);
            txtMaterialName.ReadOnly = true;

            // 添加控件到面板
            panel.Controls.AddRange(new Control[] {
                lblBOMCode, txtBOMCode,
                lblBOMVersion, txtBOMVersion,
                lblPlanId, txtPlanId, btnSelectPlan,
                lblProductName, txtProductName,
                lblSpecification, txtSpecification,
                lblUnitName, txtUnitName,
                lblMaterialId, txtMaterialId, btnSelectMaterial,
                lblMaterialCode, txtMaterialCode,
                lblMaterialName, txtMaterialName
            });
        }

        private void CreateButtons(Panel panel)
        {
            // 新增按钮
            btnAdd = new Button();
            btnAdd.Text = "新增BOM";
            btnAdd.Size = new Size(100, 30);
            btnAdd.Location = new Point(20, 10);
            btnAdd.BackColor = Color.LightGreen;
            btnAdd.Click += BtnAdd_Click;

            // 清空按钮
            btnClear = new Button();
            btnClear.Text = "清空输入";
            btnClear.Size = new Size(100, 30);
            btnClear.Location = new Point(140, 10);
            btnClear.BackColor = Color.LightYellow;
            btnClear.Click += BtnClear_Click;

            // 刷新按钮
            btnRefresh = new Button();
            btnRefresh.Text = "刷新数据";
            btnRefresh.Size = new Size(100, 30);
            btnRefresh.Location = new Point(260, 10);
            btnRefresh.BackColor = Color.LightBlue;
            btnRefresh.Click += BtnRefresh_Click;

            // 添加按钮到面板
            panel.Controls.AddRange(new Control[] { btnAdd, btnClear, btnRefresh });
        }

        private async void LoadBOMData()
        {
            try
            {
                btnRefresh.Enabled = false;
                btnRefresh.Text = "加载中...";

                var apiResponse = await ApiRequestHelper.GetAsync<BOMApiResponse>("api/BOM/GetBOM");

                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200 && apiResponse.Data.data != null)
                {
                    SetupDataGridView();
                    LoadDataToGrid(apiResponse.Data.data);
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"获取数据失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnRefresh.Enabled = true;
                btnRefresh.Text = "刷新数据";
            }
        }

        private void SetupDataGridView()
        {
            dgvBOM.Columns.Clear();

            // 添加列并设置标题
            dgvBOM.Columns.Add("BOMCode", "BOM编号");
            dgvBOM.Columns.Add("BOMVertion", "BOM版本");
            dgvBOM.Columns.Add("PlanId", "生产计划ID");
            dgvBOM.Columns.Add("ProductName", "产品名称");
            dgvBOM.Columns.Add("Specification", "规格型号");
            dgvBOM.Columns.Add("UnitName", "单位");
            dgvBOM.Columns.Add("MaterialId", "物料ID");
            dgvBOM.Columns.Add("MaterialCode", "物料编号");
            dgvBOM.Columns.Add("MaterialName", "物料名称");

            // 设置列宽
            dgvBOM.Columns["BOMCode"].Width = 120;
            dgvBOM.Columns["BOMVertion"].Width = 100;
            dgvBOM.Columns["PlanId"].Width = 100;
            dgvBOM.Columns["ProductName"].Width = 120;
            dgvBOM.Columns["Specification"].Width = 120;
            dgvBOM.Columns["UnitName"].Width = 80;
            dgvBOM.Columns["MaterialId"].Width = 100;
            dgvBOM.Columns["MaterialCode"].Width = 120;
            dgvBOM.Columns["MaterialName"].Width = 120;

            // 设置标题行样式
            dgvBOM.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
            dgvBOM.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
            dgvBOM.ColumnHeadersDefaultCellStyle.Font = new Font(dgvBOM.Font, FontStyle.Bold);
            dgvBOM.ColumnHeadersHeight = 35;
            dgvBOM.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

            // 设置交替行颜色
            dgvBOM.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
        }

        private void LoadDataToGrid(List<BOMData> bomList)
        {
            dgvBOM.Rows.Clear();

            foreach (var bom in bomList)
            {
                int rowIndex = dgvBOM.Rows.Add();
                dgvBOM.Rows[rowIndex].Cells["BOMCode"].Value = bom.BOMCode;
                dgvBOM.Rows[rowIndex].Cells["BOMVertion"].Value = bom.BOMVertion;
                dgvBOM.Rows[rowIndex].Cells["PlanId"].Value = bom.PlanId;
                dgvBOM.Rows[rowIndex].Cells["ProductName"].Value = bom.ProductName;
                dgvBOM.Rows[rowIndex].Cells["Specification"].Value = bom.Specification;
                dgvBOM.Rows[rowIndex].Cells["UnitName"].Value = bom.UnitName;
                dgvBOM.Rows[rowIndex].Cells["MaterialId"].Value = bom.MaterialId;
                dgvBOM.Rows[rowIndex].Cells["MaterialCode"].Value = bom.MaterialCode;
                dgvBOM.Rows[rowIndex].Cells["MaterialName"].Value = bom.MaterialName;
            }
        }

        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(txtBOMCode.Text))
            {
                MessageBox.Show("请输入BOM编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtBOMCode.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtPlanId.Text))
            {
                MessageBox.Show("请输入生产计划ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPlanId.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtMaterialId.Text))
            {
                MessageBox.Show("请输入物料ID", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMaterialId.Focus();
                return;
            }

            try
            {
                btnAdd.Enabled = false;
                btnAdd.Text = "添加中...";

                // 创建BOM数据对象
                var bomData = new BOMData
                {
                    BOMCode = txtBOMCode.Text.Trim(),
                    BOMVertion = txtBOMVersion.Text.Trim(),
                    PlanId = int.Parse(txtPlanId.Text.Trim()),
                    ProductName = txtProductName.Text.Trim(),
                    Specification = txtSpecification.Text.Trim(),
                    UnitName = txtUnitName.Text.Trim(),
                    MaterialId = int.Parse(txtMaterialId.Text.Trim()),
                    MaterialCode = txtMaterialCode.Text.Trim(),
                    MaterialName = txtMaterialName.Text.Trim()
                };

                // 发送POST请求
                var apiResponse = await ApiRequestHelper.PostAsync<ApiAddBOMResponse>("api/BOM/AddBOM", bomData);

                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    ApiRequestHelper.ShowSuccess("BOM添加成功！");
                    
                    // 标记为已分解
                    IsDecomposed = true;
                    
                    // 如果有当前生产计划，确保状态更新
                    if (CurrentPlan != null)
                    {
                        Console.WriteLine($"BOM添加成功，生产计划ID: {CurrentPlan.planId} 已标记为已分解");
                    }
                    
                    ClearInputs();
                    LoadBOMData(); // 刷新数据
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"添加失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加BOM时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnAdd.Enabled = true;
                btnAdd.Text = "新增BOM";
            }
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            ClearInputs();
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadBOMData();
        }

        private void ClearInputs()
        {
            txtBOMCode.Clear();
            txtBOMVersion.Clear();
            txtPlanId.Clear();
            txtProductName.Clear();
            txtSpecification.Clear();
            txtUnitName.Clear();
            txtMaterialId.Clear();
            txtMaterialCode.Clear();
            txtMaterialName.Clear();
            txtBOMCode.Focus();
        }

        /// <summary>
        /// 选择生产计划按钮点击事件
        /// </summary>
        private void BtnSelectPlan_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建生产计划选择窗体
                var selectPlanForm = new SelectPlan();
                if (selectPlanForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了生产计划，将计划信息填充到对应的输入框
                    if (selectPlanForm.SelectedPlan != null)
                    {
                        var plan = selectPlanForm.SelectedPlan;
                        txtPlanId.Text = plan.planId.ToString();
                        txtProductName.Text = plan.productName ?? "";
                        txtSpecification.Text = plan.specification ?? "";
                        txtUnitName.Text = plan.unitName ?? "";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开生产计划选择窗口失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 选择物料按钮点击事件
        /// </summary>
        private void BtnSelectMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建物料选择窗体
                var selectMaterialForm = new SelectMaterial();
                if (selectMaterialForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了物料，将物料信息填充到对应的输入框
                    if (selectMaterialForm.SelectedMaterial != null)
                    {
                        var material = selectMaterialForm.SelectedMaterial;
                        txtMaterialId.Text = material.MaterialId.ToString();
                        txtMaterialCode.Text = material.MaterialCode ?? "";
                        txtMaterialName.Text = material.MaterialName ?? "";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开物料选择窗口失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 如果已经分解完成，设置对话框结果为OK
            if (IsDecomposed)
            {
                this.DialogResult = DialogResult.OK;
            }
            
            base.OnFormClosing(e);
        }
    }
}
